package net.qhzw.vip.qiyu.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import net.qhzw.vip.qiyu.dto.ProductVo;
import net.qhzw.vip.qiyu.entity.Product;
import net.qhzw.vip.qiyu.entity.Sku;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.param.ProductParam;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.service.*;
import net.qhzw.vip.qiyu.util.Arith;
import net.qhzw.vip.qiyu.util.Json;
import net.qhzw.vip.qiyu.util.PageParam;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 商品列表、商品发布controller
 */
@RestController
@RequestMapping("/prod/prod")
@Slf4j
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private SkuService skuService;

    @Autowired
    private ProdTagReferenceService prodTagReferenceService;

    @Autowired
    private BasketService basketService;


    @Autowired
    private ProdAuditService prodAuditService;

    @Autowired
    private MallSiteService mallSiteService;


    @Autowired
    private AdminUserService adminUserService;


    /**
     * 分页获取商品信息
     */
    @GetMapping("/page")
    public JsonResult<IPage<ProductVo>> page(PageParam<Product> page, ProductParam product) {
        // Long shopId = SecurityUtils.getLoginUser().getShopId();
        Long shopId = adminUserService.getLoginUser(SecurityUtils.getUserId()).getShopId();
        product.setShopId(shopId);
        IPage<ProductVo> pageInfo = productService.findPage(page, product);
        return JsonResult.ok(pageInfo);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{prodId}")
    public JsonResult<Product> info(@PathVariable("prodId") Long prodId) {
        Product prod = productService.getProductByProdId(prodId);
//        if (!Objects.equals(prod.getShopId(), SecurityUtils.getLoginUser().getShopId())) {
//            throw new ApiException("没有权限获取该商品规格信息");
//        }
        // List<Sku> skuList = skuService.listByProdId(prodId);
        List<Sku> skuList = skuService.list(new LambdaQueryWrapper<Sku>().eq(Sku::getProdId, prodId));
        prod.setSkuList(skuList);

        //获取分组标签
        List<Long> listTagId = prodTagReferenceService.listTagIdByProdId(prodId);
        prod.setTagList(listTagId);
        return JsonResult.ok(prod);
    }

    /**
     * 保存
     */
    @PostMapping
    public JsonResult<String> save(@Valid @RequestBody ProductParam productParam) {
        log.info("新增商品: {}", JSON.toJSONString(productParam, true));
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        checkParam(productParam);
        Product product = mapperFacade.map(productParam, Product.class);
        product.setShopId(shopId);
        product.setDeliveryMode(Json.toJsonString(productParam.getDeliveryModeVo()));
        product.setShopId(SecurityUtils.getLoginUser().getShopId());
        product.setUpdateTime(new Date());
        product.setPlatformFee(Arith.mul(productParam.getPrice(), 0.03));
        product.setStatus(2);
        product.setPutawayTime(new Date());
        product.setCreateTime(new Date());
        //Double siteFee = mallSiteService.getByShopId(shopId);
        product.setSiteFee(productParam.getSkuList().get(0).getSiteFee());
        productService.saveProduct(product);
        return JsonResult.ok();
    }

    /**
     * 修改
     */
    @PutMapping
    public JsonResult<String> update(@Valid @RequestBody ProductParam productParam) {
        log.info("修改商品: {}", JSON.toJSONString(productParam, true));
        checkParam(productParam);
        Product dbProduct = productService.getProductByProdId(productParam.getProdId());
        if (3 == dbProduct.getStatus()) {
            if (productParam.getStatus() == null) {
                throw new ApiException("请先下架后, 在修改!");
            } else if (productParam.getStatus() != 1) {
                throw new ApiException("请先下架后, 在修改!");
            }
        }
        if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getLoginUser().getShopId())) {
            return JsonResult.fail("无法修改非本店铺商品信息");
        }
        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId());
        Product product = mapperFacade.map(productParam, Product.class);
        product.setDeliveryMode(Json.toJsonString(productParam.getDeliveryModeVo()));
        product.setUpdateTime(new Date());
//        if (dbProduct.getStatus() == 0 || productParam.getStatus() == 1) {
//            product.setPutawayTime(new Date());
//        }
        dbProduct.setSkuList(dbSkus);
        productService.updateProduct(product, dbProduct);
        List<String> userIds = basketService.listUserIdByProdId(product.getProdId());
        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }
        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
        }
        return JsonResult.ok();
    }

    /**
     * 删除
     */
    public JsonResult delete(Long prodId) {
        Product dbProduct = productService.getProductByProdId(prodId);
        if (dbProduct.getStatus() == 3) {
            throw new ApiException("请先下架后, 在删除!");
        }
        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId());
        // 删除商品
        productService.removeProductByProdId(prodId);

        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
        }


        List<String> userIds = basketService.listUserIdByProdId(prodId);

        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }

        return JsonResult.ok();
    }

    /**
     * 批量删除
     */
    @DeleteMapping
    public JsonResult<Void> batchDelete(@RequestBody Long[] prodIds) {
        for (Long prodId : prodIds) {
            delete(prodId);
        }
        return JsonResult.ok();
    }

    /**
     * 更新商品状态
     */
    @PutMapping("/prodStatus")
    public JsonResult<Void> shopStatus(@RequestParam Long prodId, @RequestParam Integer prodStatus) {
        Product product = new Product();
        product.setProdId(prodId);
        product.setStatus(prodStatus);
        if (prodStatus == 1) {
            product.setPutawayTime(new Date());
        }
        productService.updateById(product);
        productService.removeProductCacheByProdId(prodId);
        List<String> userIds = basketService.listUserIdByProdId(prodId);

        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }
        return JsonResult.ok();
    }

    private void checkParam(ProductParam productParam) {
        if (CollectionUtil.isEmpty(productParam.getTagList())) {
            throw new ApiException("请选择产品分组");
        }

        Product.DeliveryModeVO deliveryMode = productParam.getDeliveryModeVo();
        boolean hasDeliverMode = deliveryMode != null
                && (deliveryMode.getHasShopDelivery() || deliveryMode.getHasUserPickUp());
//        if (!hasDeliverMode) {
//            throw new ApiException("请选择配送方式");
//        }
        if (productParam.getTotalStocks() <= 0) {
            throw new ApiException("商品库存不能小于0");
        }
        List<Sku> skuList = productParam.getSkuList();
        boolean isAllUnUse = true;
        for (Sku sku : skuList) {
            if (sku.getStatus() == 1) {
                isAllUnUse = false;
            }
        }
//        if (isAllUnUse) {
//            throw new ApiException("至少要启用一种商品规格");
//        }
    }
}
